﻿using Newtonsoft.Json.Linq;
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Web.Script.Serialization;
using System.Windows.Forms;
using System.Data.SQLite;
using System.IO;
using Newtonsoft.Json;
using System.Data.SqlClient;

namespace itChatAdmin
{
    public partial class Form1 : Form
    {
        public static String dir_database = "data";
        public static String dir_logs = "log";
        private static byte[] result = new byte[1024];
        public static volatile Boolean Thread_Allow_Running = true;
        Thread thread = null;
        //public static Queue WxMessgeQueue = new Queue();
        public static volatile String itChatDatabase = "";
        public static volatile Hashtable CommandHashTable = new Hashtable();
        public static String Loading_Msg = "";
        public static Boolean Loading_OK = false;
        public ArrayList GroupClass = new ArrayList();
        public ArrayList TableArray = new ArrayList();
        public static SQLiteConnection memSQLiteConnection = new SQLiteConnection("Data Source=:memory:");
        public static volatile String UserType = "";
        public static volatile String NickName = "";
        public static volatile String UserName = "";
        public static volatile String UserID = "";
        public static DataTable MsgSendTable = new DataTable();
        public static DataTable StrangerTable = new DataTable();
        Boolean IS_AddStranger_Running = true;
        public static Random r = new Random();
        public static DataTable MemberListTable = new DataTable();
        public static ArrayList GroupFilterdList = new ArrayList();
        public static ArrayList FriendList = new ArrayList();
        public static ArrayList StrangerList = new ArrayList();



        /// <summary>
        /// 登录itChatMaster的用户的系统账号（每次启动微信，都不相同）
        /// </summary>
        public static String WxUserName = "";
        /// <summary>
        /// 登录itChatMaster的用户的系昵称
        /// </summary>
        public static String WxNickName = "";

        public static void DoWith_itChatMasterMsg(String wxMsg)
        {
            Write_Log(wxMsg, "", 4);

            //分析群信息
            JObject json = JObject.Parse(wxMsg);
            String FromUserName = json["FromUserName"].ToString();

            //检查数据库，是否设置过滤
            SQLiteCommand mySQLiteCommand = new SQLiteCommand("", memSQLiteConnection);
            mySQLiteCommand.CommandText = "SELECT * FROM MelaGroups WHERE UserName=@UserName";
            mySQLiteCommand.Parameters.Add(new SQLiteParameter("@UserName"));
            mySQLiteCommand.Parameters["@UserName"].Value = FromUserName;
            SQLiteDataReader mySQLiteDataReader1 = mySQLiteCommand.ExecuteReader();
            if (mySQLiteDataReader1.Read())
            {
                Boolean IsGetStrangers = Boolean.Parse(mySQLiteDataReader1["IsGetStrangers"].ToString().Trim());
                if (IsGetStrangers == false) return;
            }
            mySQLiteDataReader1.Close();

            JArray array = JArray.Parse(json["User"]["MemberList"].ToString());
            if (FriendList.Count == 0)
            {
                mySQLiteCommand.CommandText = "SELECT UserName FROM MelaFriends";
                SQLiteDataReader mySQLiteDataReader = mySQLiteCommand.ExecuteReader();
                while (mySQLiteDataReader.Read())
                {
                    FriendList.Add(mySQLiteDataReader["UserName"]);
                }
                mySQLiteDataReader.Close();
            }

            foreach (JObject m in array)
            {
                String UserName = m["UserName"].ToString().Trim();
                String RemarkPYQuanPin = m["RemarkPYQuanPin"].ToString().Trim();
                String DisplayName = m["DisplayName"].ToString().Trim();
                String KeyWord = m["KeyWord"].ToString().Trim();
                String PYInitial = m["PYInitial"].ToString().Trim();
                String Uin = m["Uin"].ToString().Trim();
                String MemberList = m["MemberList"].ToString().Trim();
                String MemberStatus = m["MemberStatus"].ToString().Trim();
                String PYQuanPin = m["PYQuanPin"].ToString().Trim();
                String RemarkPYInitial = m["RemarkPYInitial"].ToString().Trim();
                String NickName = m["NickName"].ToString().Trim();
                String AttrStatus = m["AttrStatus"].ToString().Trim();

                foreach (String user in FriendList)
                {
                    if (user == UserName) continue;
                }

                mySQLiteCommand.CommandText = "SELECT count(*) FROM MelaStranger WHERE NickName=@NickName";
                mySQLiteCommand.Parameters.Add(new SQLiteParameter("@NickName"));
                mySQLiteCommand.Parameters["@NickName"].Value = UserName;

                object i = mySQLiteCommand.ExecuteScalar();
                mySQLiteCommand.Parameters.Clear();

                if (int.Parse(i.ToString()) > 0)
                {
                    mySQLiteCommand.CommandText = @"UPDATE MelaStranger SET 
UserName=@UserName,
RemarkPYQuanPin=@RemarkPYQuanPin,
DisplayName=@DisplayName,
KeyWord=@KeyWord,
PYInitial=@PYInitial,
Uin=@Uin,
MemberList=@MemberList,
MemberStatus=@MemberStatus,
PYQuanPin=@PYQuanPin,
RemarkPYInitial=@RemarkPYInitial,
AttrStatus=@AttrStatus
WHERE NickName=@NickName";
                    mySQLiteCommand.Parameters.Add(new SQLiteParameter("@UserName"));
                    mySQLiteCommand.Parameters.Add(new SQLiteParameter("@RemarkPYQuanPin"));
                    mySQLiteCommand.Parameters.Add(new SQLiteParameter("@DisplayName"));
                    mySQLiteCommand.Parameters.Add(new SQLiteParameter("@KeyWord"));
                    mySQLiteCommand.Parameters.Add(new SQLiteParameter("@PYInitial"));
                    mySQLiteCommand.Parameters.Add(new SQLiteParameter("@Uin"));
                    mySQLiteCommand.Parameters.Add(new SQLiteParameter("@MemberList"));
                    mySQLiteCommand.Parameters.Add(new SQLiteParameter("@MemberStatus"));
                    mySQLiteCommand.Parameters.Add(new SQLiteParameter("@PYQuanPin"));
                    mySQLiteCommand.Parameters.Add(new SQLiteParameter("@RemarkPYInitial"));
                    mySQLiteCommand.Parameters.Add(new SQLiteParameter("@AttrStatus"));
                    mySQLiteCommand.Parameters.Add(new SQLiteParameter("@NickName"));


                    mySQLiteCommand.Parameters["@UserName"].Value = UserName;
                    mySQLiteCommand.Parameters["@RemarkPYQuanPin"].Value = RemarkPYQuanPin;
                    mySQLiteCommand.Parameters["@DisplayName"].Value = DisplayName;
                    mySQLiteCommand.Parameters["@KeyWord"].Value = KeyWord;
                    mySQLiteCommand.Parameters["@PYInitial"].Value = PYInitial;
                    mySQLiteCommand.Parameters["@Uin"].Value = Uin;
                    mySQLiteCommand.Parameters["@MemberList"].Value = MemberList;
                    mySQLiteCommand.Parameters["@MemberStatus"].Value = MemberStatus;
                    mySQLiteCommand.Parameters["@PYQuanPin"].Value = PYQuanPin;
                    mySQLiteCommand.Parameters["@RemarkPYInitial"].Value = RemarkPYInitial;
                    mySQLiteCommand.Parameters["@NickName"].Value = NickName;
                    mySQLiteCommand.Parameters["@AttrStatus"].Value = AttrStatus;

                }
                else
                {
                    mySQLiteCommand.CommandText = @"INSERT INTO MelaStranger (
UserName,
RemarkPYQuanPin,
DisplayName,
KeyWord,
PYInitial,
Uin,
MemberList,
MemberStatus,
PYQuanPin,
RemarkPYInitial,
NickName,
AttrStatus
) VALUES(
@UserName,
@RemarkPYQuanPin,
@DisplayName,
@KeyWord,
@PYInitial,
@Uin,
@MemberList,
@MemberStatus,
@PYQuanPin,
@RemarkPYInitial,
@NickName,
@AttrStatus
) ";
                    mySQLiteCommand.Parameters.Add(new SQLiteParameter("@UserName"));
                    mySQLiteCommand.Parameters.Add(new SQLiteParameter("@RemarkPYQuanPin"));
                    mySQLiteCommand.Parameters.Add(new SQLiteParameter("@DisplayName"));
                    mySQLiteCommand.Parameters.Add(new SQLiteParameter("@KeyWord"));
                    mySQLiteCommand.Parameters.Add(new SQLiteParameter("@PYInitial"));
                    mySQLiteCommand.Parameters.Add(new SQLiteParameter("@Uin"));
                    mySQLiteCommand.Parameters.Add(new SQLiteParameter("@MemberList"));
                    mySQLiteCommand.Parameters.Add(new SQLiteParameter("@MemberStatus"));
                    mySQLiteCommand.Parameters.Add(new SQLiteParameter("@PYQuanPin"));
                    mySQLiteCommand.Parameters.Add(new SQLiteParameter("@RemarkPYInitial"));
                    mySQLiteCommand.Parameters.Add(new SQLiteParameter("@AttrStatus"));
                    mySQLiteCommand.Parameters.Add(new SQLiteParameter("@NickName"));


                    mySQLiteCommand.Parameters["@UserName"].Value = UserName;
                    mySQLiteCommand.Parameters["@RemarkPYQuanPin"].Value = RemarkPYQuanPin;
                    mySQLiteCommand.Parameters["@DisplayName"].Value = DisplayName;
                    mySQLiteCommand.Parameters["@KeyWord"].Value = KeyWord;
                    mySQLiteCommand.Parameters["@PYInitial"].Value = PYInitial;
                    mySQLiteCommand.Parameters["@Uin"].Value = Uin;
                    mySQLiteCommand.Parameters["@MemberList"].Value = MemberList;
                    mySQLiteCommand.Parameters["@MemberStatus"].Value = MemberStatus;
                    mySQLiteCommand.Parameters["@PYQuanPin"].Value = PYQuanPin;
                    mySQLiteCommand.Parameters["@RemarkPYInitial"].Value = RemarkPYInitial;
                    mySQLiteCommand.Parameters["@NickName"].Value = NickName;
                    mySQLiteCommand.Parameters["@AttrStatus"].Value = AttrStatus;
                }
                mySQLiteCommand.ExecuteNonQuery();
                WriteToDBInDisk(mySQLiteCommand);
                mySQLiteCommand.Parameters.Clear();
            }


        }


        public void ShowWxHeadImages()
        {
            Object command = new
            {
                cmd = WX_COMMAND.get_head_img.ToString(),
                data_0 = "",
                data_1 = "",
                data_2 = "",
                data_3 = ""
            };
            String msg = SendCommnadTo_itChat(command);

        }

        public Form1()
        {
            InitializeComponent();

            CheckAppConfig();

            memSQLiteConnection.Open();

            Thread myThreadLoading = new Thread(new ThreadStart(ShowLoadingFrom));
            myThreadLoading.Start();

            //命令控制HASH表初始化
            Loading_Msg = "初始化控制指令列表......";
            CommandHashTableInit();
            //检查系统参数配置
            Loading_Msg = "检查系统配置参数......";
            //启动Web服务
            Loading_Msg = "启动Web Server......";
            Start_WebServers();

            //初始化数据表字段内容
            Datatable_Init();

            //获取uid,检查数据库，使用线程在后台处理
            //Loading_Msg = "获取微信用户信息......";
            //Thread myThread = new Thread(new ThreadStart(GetWxUid_CheckDataBase));
            //myThread.Start();
            GetWxUid_CheckDataBase();

            //启动发信息的进程
            Thread myThread = new Thread(new ThreadStart(Thread_SendMessage));
            myThread.Start();

            Thread myThread2 = new Thread(new ThreadStart(Thread_AddStranger));
            myThread2.Start();
            //Thread_AddStranger();

            Refresh_Data();
        }

        public static void Refresh_Data()
        {
            Refresh_Friend();
            Refresh_Group();
        }

        public static void Refresh_Group()
        {
            Object command = new
            {
                cmd = WX_COMMAND.get_chatrooms.ToString(),
                data_0 = "",
                data_1 = "",
                data_2 = "",
                data_3 = ""

            };
            //向服务器发送数据
            String result = Form1.SendCommnadTo_itChat(command);
            Refresh_ChatRooms(result);
        }
        public static void Refresh_Friend()
        {
            Object command = new
            {
                cmd = WX_COMMAND.get_friends.ToString(),
                data_0 = "",
                data_1 = "",
                data_2 = "",
                data_3 = ""

            };
            //向服务器发送数据
            String result = SendCommnadTo_itChat(command);
            Form1.Write_Log(result, WX_COMMAND.get_contact.ToString(), 4);
            Refresh_Friends(result);
        }
        public static void Refresh_ChatRooms(String WxMessage)
        {
            MemberListTable.Clear();


            //JObject json = JObject.Parse(result);
            JArray json = JArray.Parse(WxMessage);
            //更新数据库及群列表

            SQLiteCommand mySQLiteCommand = new SQLiteCommand("", Form1.memSQLiteConnection);
            foreach (JObject group in json)
            {
                if (group["NickName"].ToString().Trim() == "") continue;

                mySQLiteCommand.CommandText = "SELECT count(*) FROM MelaGroups WHERE NickName=@NickName";
                mySQLiteCommand.Parameters.Add(new SQLiteParameter("@NickName"));
                mySQLiteCommand.Parameters["@NickName"].Value = group["NickName"].ToString().Trim();


                object i = mySQLiteCommand.ExecuteScalar();
                mySQLiteCommand.Parameters.Clear();


                if (int.Parse(i.ToString().Trim()) > 0)
                {
                    mySQLiteCommand.CommandText = @"UPDATE MelaGroups SET 
UserName=@UserName,
City=@City,
DisplayName=@DisplayName,
UniFriend=@UniFriend,
Self=@Self,
PYQuanPin=@PYQuanPin,
RemarkPYInitial=@RemarkPYInitial,
Sex=@Sex,
AppAccountFlag=@AppAccountFlag,
VerifyFlag=@VerifyFlag,
Province=@Province,
KeyWord=@KeyWord,
RemarkName=@RemarkName,
PYInitial=@PYInitial,
IsOwner=@IsOwner,
ChatRoomId=@ChatRoomId,
HideInputBarFlag=@HideInputBarFlag,
EncryChatRoomId=@EncryChatRoomId,
AttrStatus=@AttrStatus,
SnsFlag=@SnsFlag,
MemberCount=@MemberCount,
OwnerUin=@OwnerUin,
Alias=@Alias,
IsAdmin=@IsAdmin,
Signature=@Signature,
ContactFlag=@ContactFlag,
RemarkPYQuanPin=@RemarkPYQuanPin,
HeadImgUrl=@HeadImgUrl,
Uin=@Uin,
StarFriend=@StarFriend,
Statues=@Statues,
UpdateDataTime = @UpdateDataTime
WHERE NickName=@NickName";
                    //UpdateDataTime = @UpdateDataTime

                    mySQLiteCommand.Parameters.Add(new SQLiteParameter("@UserName"));
                    mySQLiteCommand.Parameters.Add(new SQLiteParameter("@City"));
                    mySQLiteCommand.Parameters.Add(new SQLiteParameter("@DisplayName"));
                    mySQLiteCommand.Parameters.Add(new SQLiteParameter("@UniFriend"));
                    mySQLiteCommand.Parameters.Add(new SQLiteParameter("@Self"));
                    //mySQLiteCommand.Parameters.Add(new SQLiteParameter("@MemberList"));
                    mySQLiteCommand.Parameters.Add(new SQLiteParameter("@PYQuanPin"));
                    mySQLiteCommand.Parameters.Add(new SQLiteParameter("@RemarkPYInitial"));
                    mySQLiteCommand.Parameters.Add(new SQLiteParameter("@Sex"));
                    mySQLiteCommand.Parameters.Add(new SQLiteParameter("@AppAccountFlag"));
                    mySQLiteCommand.Parameters.Add(new SQLiteParameter("@VerifyFlag"));
                    mySQLiteCommand.Parameters.Add(new SQLiteParameter("@Province"));
                    mySQLiteCommand.Parameters.Add(new SQLiteParameter("@KeyWord"));
                    mySQLiteCommand.Parameters.Add(new SQLiteParameter("@RemarkName"));
                    mySQLiteCommand.Parameters.Add(new SQLiteParameter("@PYInitial"));
                    mySQLiteCommand.Parameters.Add(new SQLiteParameter("@IsOwner"));
                    mySQLiteCommand.Parameters.Add(new SQLiteParameter("@ChatRoomId"));
                    mySQLiteCommand.Parameters.Add(new SQLiteParameter("@HideInputBarFlag"));
                    mySQLiteCommand.Parameters.Add(new SQLiteParameter("@EncryChatRoomId"));
                    mySQLiteCommand.Parameters.Add(new SQLiteParameter("@AttrStatus"));
                    mySQLiteCommand.Parameters.Add(new SQLiteParameter("@SnsFlag"));
                    mySQLiteCommand.Parameters.Add(new SQLiteParameter("@MemberCount"));
                    mySQLiteCommand.Parameters.Add(new SQLiteParameter("@OwnerUin"));
                    mySQLiteCommand.Parameters.Add(new SQLiteParameter("@Alias"));
                    mySQLiteCommand.Parameters.Add(new SQLiteParameter("@IsAdmin"));
                    mySQLiteCommand.Parameters.Add(new SQLiteParameter("@Signature"));
                    mySQLiteCommand.Parameters.Add(new SQLiteParameter("@ContactFlag"));
                    mySQLiteCommand.Parameters.Add(new SQLiteParameter("@RemarkPYQuanPin"));
                    mySQLiteCommand.Parameters.Add(new SQLiteParameter("@HeadImgUrl"));
                    mySQLiteCommand.Parameters.Add(new SQLiteParameter("@Uin"));
                    mySQLiteCommand.Parameters.Add(new SQLiteParameter("@StarFriend"));
                    mySQLiteCommand.Parameters.Add(new SQLiteParameter("@Statues"));
                    mySQLiteCommand.Parameters.Add(new SQLiteParameter("@NickName"));
                    mySQLiteCommand.Parameters.Add(new SQLiteParameter("@UpdateDataTime"));

                    mySQLiteCommand.Parameters["@UserName"].Value = group["UserName"].ToString().Trim();
                    mySQLiteCommand.Parameters["@City"].Value = group["City"].ToString().Trim();
                    mySQLiteCommand.Parameters["@DisplayName"].Value = group["DisplayName"].ToString().Trim();
                    mySQLiteCommand.Parameters["@UniFriend"].Value = group["UniFriend"].ToString().Trim();
                    mySQLiteCommand.Parameters["@Self"].Value = group["Self"].ToString().Trim();
                    //mySQLiteCommand.Parameters["@MemberList"].Value = group["MemberList"].ToString().Trim();
                    mySQLiteCommand.Parameters["@PYQuanPin"].Value = group["PYQuanPin"].ToString().Trim();
                    mySQLiteCommand.Parameters["@RemarkPYInitial"].Value = group["RemarkPYInitial"].ToString().Trim();
                    mySQLiteCommand.Parameters["@Sex"].Value = group["Sex"].ToString().Trim();
                    mySQLiteCommand.Parameters["@AppAccountFlag"].Value = group["AppAccountFlag"].ToString().Trim();
                    mySQLiteCommand.Parameters["@VerifyFlag"].Value = group["VerifyFlag"].ToString().Trim();
                    mySQLiteCommand.Parameters["@Province"].Value = group["Province"].ToString().Trim();
                    mySQLiteCommand.Parameters["@KeyWord"].Value = group["KeyWord"].ToString().Trim();
                    mySQLiteCommand.Parameters["@RemarkName"].Value = group["RemarkName"].ToString().Trim();
                    mySQLiteCommand.Parameters["@PYInitial"].Value = group["PYInitial"].ToString().Trim();
                    mySQLiteCommand.Parameters["@IsOwner"].Value = group["IsOwner"].ToString().Trim();
                    mySQLiteCommand.Parameters["@ChatRoomId"].Value = group["ChatRoomId"].ToString().Trim();
                    mySQLiteCommand.Parameters["@HideInputBarFlag"].Value = group["HideInputBarFlag"].ToString().Trim();
                    mySQLiteCommand.Parameters["@EncryChatRoomId"].Value = group["EncryChatRoomId"].ToString().Trim();
                    mySQLiteCommand.Parameters["@AttrStatus"].Value = group["AttrStatus"].ToString().Trim();
                    mySQLiteCommand.Parameters["@SnsFlag"].Value = group["SnsFlag"].ToString().Trim();
                    mySQLiteCommand.Parameters["@MemberCount"].Value = group["MemberCount"].ToString().Trim();
                    mySQLiteCommand.Parameters["@OwnerUin"].Value = group["OwnerUin"].ToString().Trim();
                    mySQLiteCommand.Parameters["@Alias"].Value = group["Alias"].ToString().Trim();
                    mySQLiteCommand.Parameters["@IsAdmin"].Value = group["IsAdmin"].ToString().Trim();
                    mySQLiteCommand.Parameters["@Signature"].Value = group["Signature"].ToString().Trim();
                    mySQLiteCommand.Parameters["@ContactFlag"].Value = group["ContactFlag"].ToString().Trim();
                    mySQLiteCommand.Parameters["@RemarkPYQuanPin"].Value = group["RemarkPYQuanPin"].ToString().Trim();
                    mySQLiteCommand.Parameters["@HeadImgUrl"].Value = group["HeadImgUrl"].ToString().Trim();
                    mySQLiteCommand.Parameters["@Uin"].Value = group["Uin"].ToString().Trim();
                    mySQLiteCommand.Parameters["@StarFriend"].Value = group["StarFriend"].ToString().Trim();
                    mySQLiteCommand.Parameters["@Statues"].Value = group["Statues"].ToString().Trim();
                    mySQLiteCommand.Parameters["@NickName"].Value = group["NickName"].ToString().Trim();
                    mySQLiteCommand.Parameters["@UpdateDataTime"].Value = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"); //有错！
                }
                else
                {
                    mySQLiteCommand.CommandText = @"INSERT INTO MelaGroups(
UserName,City,DisplayName,UniFriend,Self,PYQuanPin,RemarkPYInitial,Sex,AppAccountFlag,VerifyFlag,Province,KeyWord,RemarkName,PYInitial,IsOwner,ChatRoomId,HideInputBarFlag,EncryChatRoomId,AttrStatus,SnsFlag,MemberCount,OwnerUin,Alias,IsAdmin,Signature,ContactFlag,NickName,RemarkPYQuanPin,HeadImgUrl,Uin,StarFriend,Statues
) VALUES(@UserName,@City,@DisplayName,@UniFriend,@Self,@PYQuanPin,@RemarkPYInitial,@Sex,@AppAccountFlag,@VerifyFlag,@Province,@KeyWord,@RemarkName,@PYInitial,@IsOwner,@ChatRoomId,@HideInputBarFlag,@EncryChatRoomId,@AttrStatus,@SnsFlag,@MemberCount,@OwnerUin,@Alias,@IsAdmin,@Signature,@ContactFlag,@NickName,@RemarkPYQuanPin,@HeadImgUrl,@Uin,@StarFriend,@Statues)";
                    mySQLiteCommand.Parameters.Add(new SQLiteParameter("@UserName"));
                    mySQLiteCommand.Parameters.Add(new SQLiteParameter("@City"));
                    mySQLiteCommand.Parameters.Add(new SQLiteParameter("@DisplayName"));
                    mySQLiteCommand.Parameters.Add(new SQLiteParameter("@UniFriend"));
                    mySQLiteCommand.Parameters.Add(new SQLiteParameter("@Self"));
                    //mySQLiteCommand.Parameters.Add(new SQLiteParameter("@MemberList"));
                    mySQLiteCommand.Parameters.Add(new SQLiteParameter("@PYQuanPin"));
                    mySQLiteCommand.Parameters.Add(new SQLiteParameter("@RemarkPYInitial"));
                    mySQLiteCommand.Parameters.Add(new SQLiteParameter("@Sex"));
                    mySQLiteCommand.Parameters.Add(new SQLiteParameter("@AppAccountFlag"));
                    mySQLiteCommand.Parameters.Add(new SQLiteParameter("@VerifyFlag"));
                    mySQLiteCommand.Parameters.Add(new SQLiteParameter("@Province"));
                    mySQLiteCommand.Parameters.Add(new SQLiteParameter("@KeyWord"));
                    mySQLiteCommand.Parameters.Add(new SQLiteParameter("@RemarkName"));
                    mySQLiteCommand.Parameters.Add(new SQLiteParameter("@PYInitial"));
                    mySQLiteCommand.Parameters.Add(new SQLiteParameter("@IsOwner"));
                    mySQLiteCommand.Parameters.Add(new SQLiteParameter("@ChatRoomId"));
                    mySQLiteCommand.Parameters.Add(new SQLiteParameter("@HideInputBarFlag"));
                    mySQLiteCommand.Parameters.Add(new SQLiteParameter("@EncryChatRoomId"));
                    mySQLiteCommand.Parameters.Add(new SQLiteParameter("@AttrStatus"));
                    mySQLiteCommand.Parameters.Add(new SQLiteParameter("@SnsFlag"));
                    mySQLiteCommand.Parameters.Add(new SQLiteParameter("@MemberCount"));
                    mySQLiteCommand.Parameters.Add(new SQLiteParameter("@OwnerUin"));
                    mySQLiteCommand.Parameters.Add(new SQLiteParameter("@Alias"));
                    mySQLiteCommand.Parameters.Add(new SQLiteParameter("@IsAdmin"));
                    mySQLiteCommand.Parameters.Add(new SQLiteParameter("@Signature"));
                    mySQLiteCommand.Parameters.Add(new SQLiteParameter("@ContactFlag"));
                    mySQLiteCommand.Parameters.Add(new SQLiteParameter("@NickName"));
                    mySQLiteCommand.Parameters.Add(new SQLiteParameter("@RemarkPYQuanPin"));
                    mySQLiteCommand.Parameters.Add(new SQLiteParameter("@HeadImgUrl"));
                    mySQLiteCommand.Parameters.Add(new SQLiteParameter("@Uin"));
                    mySQLiteCommand.Parameters.Add(new SQLiteParameter("@StarFriend"));
                    mySQLiteCommand.Parameters.Add(new SQLiteParameter("@Statues"));
                    //mySQLiteCommand.Parameters.Add(new SQLiteParameter("@UpdateDataTime"));

                    mySQLiteCommand.Parameters["@UserName"].Value = group["UserName"].ToString().Trim();
                    mySQLiteCommand.Parameters["@City"].Value = group["City"].ToString().Trim();
                    mySQLiteCommand.Parameters["@DisplayName"].Value = group["DisplayName"].ToString().Trim();
                    mySQLiteCommand.Parameters["@UniFriend"].Value = group["UniFriend"].ToString().Trim();
                    mySQLiteCommand.Parameters["@Self"].Value = group["Self"].ToString().Trim();
                    //mySQLiteCommand.Parameters["@MemberList"].Value = group["MemberList"].ToString().Trim();
                    mySQLiteCommand.Parameters["@PYQuanPin"].Value = group["PYQuanPin"].ToString().Trim();
                    mySQLiteCommand.Parameters["@RemarkPYInitial"].Value = group["RemarkPYInitial"].ToString().Trim();
                    mySQLiteCommand.Parameters["@Sex"].Value = group["Sex"].ToString().Trim();
                    mySQLiteCommand.Parameters["@AppAccountFlag"].Value = group["AppAccountFlag"].ToString().Trim();
                    mySQLiteCommand.Parameters["@VerifyFlag"].Value = group["VerifyFlag"].ToString().Trim();
                    mySQLiteCommand.Parameters["@Province"].Value = group["Province"].ToString().Trim();
                    mySQLiteCommand.Parameters["@KeyWord"].Value = group["KeyWord"].ToString().Trim();
                    mySQLiteCommand.Parameters["@RemarkName"].Value = group["RemarkName"].ToString().Trim();
                    mySQLiteCommand.Parameters["@PYInitial"].Value = group["PYInitial"].ToString().Trim();
                    mySQLiteCommand.Parameters["@IsOwner"].Value = group["IsOwner"].ToString().Trim();
                    mySQLiteCommand.Parameters["@ChatRoomId"].Value = group["ChatRoomId"].ToString().Trim();
                    mySQLiteCommand.Parameters["@HideInputBarFlag"].Value = group["HideInputBarFlag"].ToString().Trim();
                    mySQLiteCommand.Parameters["@EncryChatRoomId"].Value = group["EncryChatRoomId"].ToString().Trim();
                    mySQLiteCommand.Parameters["@AttrStatus"].Value = group["AttrStatus"].ToString().Trim();
                    mySQLiteCommand.Parameters["@SnsFlag"].Value = group["SnsFlag"].ToString().Trim();
                    mySQLiteCommand.Parameters["@MemberCount"].Value = group["MemberCount"].ToString().Trim();
                    mySQLiteCommand.Parameters["@OwnerUin"].Value = group["OwnerUin"].ToString().Trim();
                    mySQLiteCommand.Parameters["@Alias"].Value = group["Alias"].ToString().Trim();
                    mySQLiteCommand.Parameters["@IsAdmin"].Value = group["IsAdmin"].ToString().Trim();
                    mySQLiteCommand.Parameters["@Signature"].Value = group["Signature"].ToString().Trim();
                    mySQLiteCommand.Parameters["@ContactFlag"].Value = group["ContactFlag"].ToString().Trim();
                    mySQLiteCommand.Parameters["@NickName"].Value = group["NickName"].ToString().Trim();
                    mySQLiteCommand.Parameters["@RemarkPYQuanPin"].Value = group["RemarkPYQuanPin"].ToString().Trim();
                    mySQLiteCommand.Parameters["@HeadImgUrl"].Value = group["HeadImgUrl"].ToString().Trim();
                    mySQLiteCommand.Parameters["@Uin"].Value = group["Uin"].ToString().Trim();
                    mySQLiteCommand.Parameters["@StarFriend"].Value = group["StarFriend"].ToString().Trim();
                    mySQLiteCommand.Parameters["@Statues"].Value = group["Statues"].ToString().Trim();
                    //mySQLiteCommand.Parameters["@UpdateDataTime"].Value = "(datetime('now', 'localtime')";

                }

                mySQLiteCommand.ExecuteNonQuery();
                WriteToDBInDisk(mySQLiteCommand);
                mySQLiteCommand.Parameters.Clear();
            }

        }

        public static void Refresh_Friends(String WxMessage)
        {
            //JObject json = JObject.Parse(result);
            JArray json = JArray.Parse(WxMessage);
            //更新数据库及群列表

            SQLiteCommand mySQLiteCommand = new SQLiteCommand("", Form1.memSQLiteConnection);
            foreach (JObject group in json)
            {
                if (group["NickName"].ToString().Trim() == "") continue;

                mySQLiteCommand.CommandText = "SELECT count(*) FROM MelaFriends WHERE NickName=@NickName";
                mySQLiteCommand.Parameters.Add(new SQLiteParameter("@NickName"));
                mySQLiteCommand.Parameters["@NickName"].Value = group["NickName"].ToString().Trim();

                object i = mySQLiteCommand.ExecuteScalar();
                mySQLiteCommand.Parameters.Clear();

                if (int.Parse(i.ToString().Trim()) > 0)
                {
                    mySQLiteCommand.CommandText = @"UPDATE MelaFriends SET 
UserName=@UserName,
City=@City,
DisplayName=@DisplayName,
UniFriend=@UniFriend,
OwnerUin=@OwnerUin,
MemberList=@MemberList,
PYQuanPin=@PYQuanPin,
RemarkPYInitial=@RemarkPYInitial,
Uin=@Uin,
AppAccountFlag=@AppAccountFlag,
VerifyFlag=@VerifyFlag,
Province=@Province,
KeyWord=@KeyWord,
RemarkName=@RemarkName,
PYInitial=@PYInitial,
ChatRoomId=@ChatRoomId,
HideInputBarFlag=@HideInputBarFlag,
HeadImgFlag=@HeadImgFlag,
EncryChatRoomId=@EncryChatRoomId,
AttrStatus=@AttrStatus,
SnsFlag=@SnsFlag,
MemberCount=@MemberCount,
IsOwner=@IsOwner,
WebWxPluginSwitch=@WebWxPluginSwitch,
Alias=@Alias,
Signature=@Signature,
ContactFlag=@ContactFlag,
RemarkPYQuanPin=@RemarkPYQuanPin,
HeadImgUrl=@HeadImgUrl,
Sex=@Sex,
StarFriend=@StarFriend,
Statues=@Statues
WHERE NickName=@NickName";
                    //UpdateDataTime = @UpdateDataTime

                    mySQLiteCommand.Parameters.Add(new SQLiteParameter("@UserName"));
                    mySQLiteCommand.Parameters.Add(new SQLiteParameter("@City"));
                    mySQLiteCommand.Parameters.Add(new SQLiteParameter("@DisplayName"));
                    mySQLiteCommand.Parameters.Add(new SQLiteParameter("@UniFriend"));
                    mySQLiteCommand.Parameters.Add(new SQLiteParameter("@OwnerUin"));
                    mySQLiteCommand.Parameters.Add(new SQLiteParameter("@MemberList"));
                    mySQLiteCommand.Parameters.Add(new SQLiteParameter("@PYQuanPin"));
                    mySQLiteCommand.Parameters.Add(new SQLiteParameter("@RemarkPYInitial"));
                    mySQLiteCommand.Parameters.Add(new SQLiteParameter("@Uin"));
                    mySQLiteCommand.Parameters.Add(new SQLiteParameter("@AppAccountFlag"));
                    mySQLiteCommand.Parameters.Add(new SQLiteParameter("@VerifyFlag"));
                    mySQLiteCommand.Parameters.Add(new SQLiteParameter("@Province"));
                    mySQLiteCommand.Parameters.Add(new SQLiteParameter("@KeyWord"));
                    mySQLiteCommand.Parameters.Add(new SQLiteParameter("@RemarkName"));
                    mySQLiteCommand.Parameters.Add(new SQLiteParameter("@PYInitial"));
                    mySQLiteCommand.Parameters.Add(new SQLiteParameter("@ChatRoomId"));
                    mySQLiteCommand.Parameters.Add(new SQLiteParameter("@HideInputBarFlag"));
                    mySQLiteCommand.Parameters.Add(new SQLiteParameter("@HeadImgFlag"));
                    mySQLiteCommand.Parameters.Add(new SQLiteParameter("@EncryChatRoomId"));
                    mySQLiteCommand.Parameters.Add(new SQLiteParameter("@AttrStatus"));
                    mySQLiteCommand.Parameters.Add(new SQLiteParameter("@SnsFlag"));
                    mySQLiteCommand.Parameters.Add(new SQLiteParameter("@MemberCount"));
                    mySQLiteCommand.Parameters.Add(new SQLiteParameter("@IsOwner"));
                    mySQLiteCommand.Parameters.Add(new SQLiteParameter("@WebWxPluginSwitch"));
                    mySQLiteCommand.Parameters.Add(new SQLiteParameter("@Alias"));
                    mySQLiteCommand.Parameters.Add(new SQLiteParameter("@Signature"));
                    mySQLiteCommand.Parameters.Add(new SQLiteParameter("@ContactFlag"));
                    mySQLiteCommand.Parameters.Add(new SQLiteParameter("@RemarkPYQuanPin"));
                    mySQLiteCommand.Parameters.Add(new SQLiteParameter("@HeadImgUrl"));
                    mySQLiteCommand.Parameters.Add(new SQLiteParameter("@Sex"));
                    mySQLiteCommand.Parameters.Add(new SQLiteParameter("@StarFriend"));
                    mySQLiteCommand.Parameters.Add(new SQLiteParameter("@Statues"));
                    mySQLiteCommand.Parameters.Add(new SQLiteParameter("@NickName"));



                    mySQLiteCommand.Parameters["@UserName"].Value = group["UserName"].ToString().Trim();
                    mySQLiteCommand.Parameters["@City"].Value = group["City"].ToString().Trim();
                    mySQLiteCommand.Parameters["@DisplayName"].Value = group["DisplayName"].ToString().Trim();
                    mySQLiteCommand.Parameters["@UniFriend"].Value = group["UniFriend"].ToString().Trim();
                    mySQLiteCommand.Parameters["@OwnerUin"].Value = group["OwnerUin"].ToString().Trim();
                    mySQLiteCommand.Parameters["@MemberList"].Value = group["MemberList"].ToString().Trim();
                    mySQLiteCommand.Parameters["@PYQuanPin"].Value = group["PYQuanPin"].ToString().Trim();
                    mySQLiteCommand.Parameters["@RemarkPYInitial"].Value = group["RemarkPYInitial"].ToString().Trim();
                    mySQLiteCommand.Parameters["@Uin"].Value = group["Uin"].ToString().Trim();
                    mySQLiteCommand.Parameters["@AppAccountFlag"].Value = group["AppAccountFlag"].ToString().Trim();
                    mySQLiteCommand.Parameters["@VerifyFlag"].Value = group["VerifyFlag"].ToString().Trim();
                    mySQLiteCommand.Parameters["@Province"].Value = group["Province"].ToString().Trim();
                    mySQLiteCommand.Parameters["@KeyWord"].Value = group["KeyWord"].ToString().Trim();
                    mySQLiteCommand.Parameters["@RemarkName"].Value = group["RemarkName"].ToString().Trim();
                    mySQLiteCommand.Parameters["@PYInitial"].Value = group["PYInitial"].ToString().Trim();
                    mySQLiteCommand.Parameters["@ChatRoomId"].Value = group["ChatRoomId"].ToString().Trim();
                    mySQLiteCommand.Parameters["@HideInputBarFlag"].Value = group["HideInputBarFlag"].ToString().Trim();
                    if (group["HeadImgFlag"] != null)
                    {
                        mySQLiteCommand.Parameters["@HeadImgFlag"].Value = group["HeadImgFlag"].ToString().Trim();
                    }
                    else
                    {
                        mySQLiteCommand.Parameters["@HeadImgFlag"].Value = "";

                    }
                    mySQLiteCommand.Parameters["@EncryChatRoomId"].Value = group["EncryChatRoomId"].ToString().Trim();
                    mySQLiteCommand.Parameters["@AttrStatus"].Value = group["AttrStatus"].ToString().Trim();
                    mySQLiteCommand.Parameters["@SnsFlag"].Value = group["SnsFlag"].ToString().Trim();
                    mySQLiteCommand.Parameters["@MemberCount"].Value = group["MemberCount"].ToString().Trim();

                    if (group["IsOwner"] != null)
                    {
                        mySQLiteCommand.Parameters["@IsOwner"].Value = group["IsOwner"].ToString().Trim();
                    }
                    else
                    {
                        mySQLiteCommand.Parameters["@IsOwner"].Value = "";
                    }

                    if (group["WebWxPluginSwitch"] != null)
                    {
                        mySQLiteCommand.Parameters["@WebWxPluginSwitch"].Value = group["WebWxPluginSwitch"].ToString().Trim();
                    }
                    else
                    {
                        mySQLiteCommand.Parameters["@WebWxPluginSwitch"].Value = "";
                    }
                    mySQLiteCommand.Parameters["@Alias"].Value = group["Alias"].ToString().Trim();
                    mySQLiteCommand.Parameters["@Signature"].Value = group["Signature"].ToString().Trim();
                    mySQLiteCommand.Parameters["@ContactFlag"].Value = group["ContactFlag"].ToString().Trim();
                    mySQLiteCommand.Parameters["@RemarkPYQuanPin"].Value = group["RemarkPYQuanPin"].ToString().Trim();
                    mySQLiteCommand.Parameters["@HeadImgUrl"].Value = group["HeadImgUrl"].ToString().Trim();
                    mySQLiteCommand.Parameters["@Sex"].Value = group["Sex"].ToString().Trim();
                    mySQLiteCommand.Parameters["@StarFriend"].Value = group["StarFriend"].ToString().Trim();
                    mySQLiteCommand.Parameters["@Statues"].Value = group["Statues"].ToString().Trim();
                    mySQLiteCommand.Parameters["@NickName"].Value = group["NickName"].ToString().Trim();
                }
                else
                {
                    mySQLiteCommand.CommandText = @"INSERT INTO MelaFriends(UserName,
City,
DisplayName,
UniFriend,
OwnerUin,
MemberList,
PYQuanPin,
RemarkPYInitial,
Uin,
AppAccountFlag,
VerifyFlag,
Province,
KeyWord,
RemarkName,
PYInitial,
ChatRoomId,
HideInputBarFlag,
HeadImgFlag,
EncryChatRoomId,
AttrStatus,
SnsFlag,
MemberCount,
IsOwner,
WebWxPluginSwitch,
Alias,
Signature,
ContactFlag,
NickName,
RemarkPYQuanPin,
HeadImgUrl,
Sex,
StarFriend,
Statues) VALUES(@UserName,
@City,
@DisplayName,
@UniFriend,
@OwnerUin,
@MemberList,
@PYQuanPin,
@RemarkPYInitial,
@Uin,
@AppAccountFlag,
@VerifyFlag,
@Province,
@KeyWord,
@RemarkName,
@PYInitial,
@ChatRoomId,
@HideInputBarFlag,
@HeadImgFlag,
@EncryChatRoomId,
@AttrStatus,
@SnsFlag,
@MemberCount,
@IsOwner,
@WebWxPluginSwitch,
@Alias,
@Signature,
@ContactFlag,
@NickName,
@RemarkPYQuanPin,
@HeadImgUrl,
@Sex,
@StarFriend,
@Statues
)";
                    mySQLiteCommand.Parameters.Add(new SQLiteParameter("@UserName"));
                    mySQLiteCommand.Parameters.Add(new SQLiteParameter("@City"));
                    mySQLiteCommand.Parameters.Add(new SQLiteParameter("@DisplayName"));
                    mySQLiteCommand.Parameters.Add(new SQLiteParameter("@UniFriend"));
                    mySQLiteCommand.Parameters.Add(new SQLiteParameter("@OwnerUin"));
                    mySQLiteCommand.Parameters.Add(new SQLiteParameter("@MemberList"));
                    mySQLiteCommand.Parameters.Add(new SQLiteParameter("@PYQuanPin"));
                    mySQLiteCommand.Parameters.Add(new SQLiteParameter("@RemarkPYInitial"));
                    mySQLiteCommand.Parameters.Add(new SQLiteParameter("@Uin"));
                    mySQLiteCommand.Parameters.Add(new SQLiteParameter("@AppAccountFlag"));
                    mySQLiteCommand.Parameters.Add(new SQLiteParameter("@VerifyFlag"));
                    mySQLiteCommand.Parameters.Add(new SQLiteParameter("@Province"));
                    mySQLiteCommand.Parameters.Add(new SQLiteParameter("@KeyWord"));
                    mySQLiteCommand.Parameters.Add(new SQLiteParameter("@RemarkName"));
                    mySQLiteCommand.Parameters.Add(new SQLiteParameter("@PYInitial"));
                    mySQLiteCommand.Parameters.Add(new SQLiteParameter("@ChatRoomId"));
                    mySQLiteCommand.Parameters.Add(new SQLiteParameter("@HideInputBarFlag"));
                    mySQLiteCommand.Parameters.Add(new SQLiteParameter("@HeadImgFlag"));
                    mySQLiteCommand.Parameters.Add(new SQLiteParameter("@EncryChatRoomId"));
                    mySQLiteCommand.Parameters.Add(new SQLiteParameter("@AttrStatus"));
                    mySQLiteCommand.Parameters.Add(new SQLiteParameter("@SnsFlag"));
                    mySQLiteCommand.Parameters.Add(new SQLiteParameter("@MemberCount"));
                    mySQLiteCommand.Parameters.Add(new SQLiteParameter("@IsOwner"));
                    mySQLiteCommand.Parameters.Add(new SQLiteParameter("@WebWxPluginSwitch"));
                    mySQLiteCommand.Parameters.Add(new SQLiteParameter("@Alias"));
                    mySQLiteCommand.Parameters.Add(new SQLiteParameter("@Signature"));
                    mySQLiteCommand.Parameters.Add(new SQLiteParameter("@ContactFlag"));
                    mySQLiteCommand.Parameters.Add(new SQLiteParameter("@NickName"));
                    mySQLiteCommand.Parameters.Add(new SQLiteParameter("@RemarkPYQuanPin"));
                    mySQLiteCommand.Parameters.Add(new SQLiteParameter("@HeadImgUrl"));
                    mySQLiteCommand.Parameters.Add(new SQLiteParameter("@Sex"));
                    mySQLiteCommand.Parameters.Add(new SQLiteParameter("@StarFriend"));
                    mySQLiteCommand.Parameters.Add(new SQLiteParameter("@Statues"));



                    mySQLiteCommand.Parameters["@UserName"].Value = group["UserName"].ToString().Trim();
                    mySQLiteCommand.Parameters["@City"].Value = group["City"].ToString().Trim();
                    mySQLiteCommand.Parameters["@DisplayName"].Value = group["DisplayName"].ToString().Trim();
                    mySQLiteCommand.Parameters["@UniFriend"].Value = group["UniFriend"].ToString().Trim();
                    mySQLiteCommand.Parameters["@OwnerUin"].Value = group["OwnerUin"].ToString().Trim();
                    mySQLiteCommand.Parameters["@MemberList"].Value = group["MemberList"].ToString().Trim();
                    mySQLiteCommand.Parameters["@PYQuanPin"].Value = group["PYQuanPin"].ToString().Trim();
                    mySQLiteCommand.Parameters["@RemarkPYInitial"].Value = group["RemarkPYInitial"].ToString().Trim();
                    mySQLiteCommand.Parameters["@Uin"].Value = group["Uin"].ToString().Trim();
                    mySQLiteCommand.Parameters["@AppAccountFlag"].Value = group["AppAccountFlag"].ToString().Trim();
                    mySQLiteCommand.Parameters["@VerifyFlag"].Value = group["VerifyFlag"].ToString().Trim();
                    mySQLiteCommand.Parameters["@Province"].Value = group["Province"].ToString().Trim();
                    mySQLiteCommand.Parameters["@KeyWord"].Value = group["KeyWord"].ToString().Trim();
                    mySQLiteCommand.Parameters["@RemarkName"].Value = group["RemarkName"].ToString().Trim();
                    mySQLiteCommand.Parameters["@PYInitial"].Value = group["PYInitial"].ToString().Trim();
                    mySQLiteCommand.Parameters["@ChatRoomId"].Value = group["ChatRoomId"].ToString().Trim();
                    mySQLiteCommand.Parameters["@HideInputBarFlag"].Value = group["HideInputBarFlag"].ToString().Trim();

                    if (group["HeadImgFlag"] != null)
                    {
                        mySQLiteCommand.Parameters["@HeadImgFlag"].Value = group["HeadImgFlag"].ToString().Trim();
                    }
                    else
                    {
                        mySQLiteCommand.Parameters["@HeadImgFlag"].Value = "";

                    }
                    mySQLiteCommand.Parameters["@EncryChatRoomId"].Value = group["EncryChatRoomId"].ToString().Trim();
                    mySQLiteCommand.Parameters["@AttrStatus"].Value = group["AttrStatus"].ToString().Trim();
                    mySQLiteCommand.Parameters["@SnsFlag"].Value = group["SnsFlag"].ToString().Trim();
                    mySQLiteCommand.Parameters["@MemberCount"].Value = group["MemberCount"].ToString().Trim();


                    if (group["IsOwner"] != null)
                    {
                        mySQLiteCommand.Parameters["@IsOwner"].Value = group["IsOwner"].ToString().Trim();

                    }
                    else
                    {
                        mySQLiteCommand.Parameters["@IsOwner"].Value = "";

                    }
                    if (group["WebWxPluginSwitch"] != null)
                    {
                        mySQLiteCommand.Parameters["@WebWxPluginSwitch"].Value = group["WebWxPluginSwitch"].ToString().Trim();

                    }
                    else
                    {
                        mySQLiteCommand.Parameters["@WebWxPluginSwitch"].Value = "";

                    }
                    mySQLiteCommand.Parameters["@Alias"].Value = group["Alias"].ToString().Trim();
                    mySQLiteCommand.Parameters["@Signature"].Value = group["Signature"].ToString().Trim();
                    mySQLiteCommand.Parameters["@ContactFlag"].Value = group["ContactFlag"].ToString().Trim();
                    mySQLiteCommand.Parameters["@NickName"].Value = group["NickName"].ToString().Trim();
                    mySQLiteCommand.Parameters["@RemarkPYQuanPin"].Value = group["RemarkPYQuanPin"].ToString().Trim();
                    mySQLiteCommand.Parameters["@HeadImgUrl"].Value = group["HeadImgUrl"].ToString().Trim();
                    mySQLiteCommand.Parameters["@Sex"].Value = group["Sex"].ToString().Trim();
                    mySQLiteCommand.Parameters["@StarFriend"].Value = group["StarFriend"].ToString().Trim();
                    mySQLiteCommand.Parameters["@Statues"].Value = group["Statues"].ToString().Trim();
                }
                mySQLiteCommand.ExecuteNonQuery();
                WriteToDBInDisk(mySQLiteCommand);
                mySQLiteCommand.Parameters.Clear();
            }

        }
        private void Thread_AddStranger()
        {
            StrangerTable.Columns.Add("NickName", typeof(string));
            StrangerTable.Columns.Add("UserName", typeof(string));
            StrangerTable.Columns.Add("IsSend", typeof(bool));
            StrangerTable.Columns.Add("IsFilterd", typeof(bool));

            //数据库信息
            SQLiteCommand memSQLiteCommand = new SQLiteCommand("", memSQLiteConnection);
            memSQLiteCommand.CommandText = @"SELECT * FROM  MelaStranger";
            SQLiteDataReader mySQLiteDataReader = memSQLiteCommand.ExecuteReader();
            while (mySQLiteDataReader.Read())
            {
                String UserName1 = mySQLiteDataReader["UserName"].ToString().Trim();
                String NickName1 = mySQLiteDataReader["NickName"].ToString().Trim();
                Boolean IsSend = Boolean.Parse(mySQLiteDataReader["IsSend"].ToString().Trim());
                Boolean IsFilterd = Boolean.Parse(mySQLiteDataReader["IsFilterd"].ToString().Trim());

                DataRow dr = StrangerTable.NewRow();
                dr["UserName"] = UserName1;
                dr["NickName"] = NickName1;
                dr["IsSend"] = IsSend;
                dr["IsFilterd"] = IsFilterd;
                StrangerTable.Rows.Add(dr);
            }

            DateTime NextRunTime = DateTime.Now;
            while (true)
            {
                if (IS_AddStranger_Running == false)
                {
                    if (NextRunTime < DateTime.Now)
                    {
                        IS_AddStranger_Running = true;

                    }
                    Thread.Sleep(500);
                }

                foreach (DataRow dr in StrangerTable.Rows)
                {

                    String NickName1 = dr["NickName"].ToString().Trim();
                    String UserName1 = dr["UserName"].ToString().Trim();
                    Boolean IsSend = Boolean.Parse(dr["IsSend"].ToString().Trim());
                    Boolean IsFilterd = Boolean.Parse(dr["IsFilterd"].ToString().Trim());

                    if (IsSend == true) continue;
                    if (IsFilterd == true) continue;

                    Object command = new
                    {
                        cmd = WX_COMMAND.add_friend.ToString(),
                        data_0 = UserName1,
                        data_1 = 2,
                        data_2 = "你好，你的签名很有正能量，互粉一下吧！",
                        data_3 = ""

                    };
                    //向服务器发送数据
                    String result = SendCommnadTo_itChat(command);
                    Write_Log(result, "add_friend", 4);
                    JObject json = JObject.Parse(result);
                    if (json["BaseResponse"]["Ret"].ToString().Trim() != "0")
                    {
                        IS_AddStranger_Running = false;
                        NextRunTime.AddMinutes(r.Next(50, 180));
                    }
                    dr["IsSend"] = true;
                    Thread.Sleep(r.Next(10000, 25000));
                }
            }
        }

      
        private void Thread_SendMessage()
        {
            //创建列
            MsgSendTable.Columns.Add("UserType", typeof(int));
            MsgSendTable.Columns.Add("UserName", typeof(string));
            MsgSendTable.Columns.Add("NickName", typeof(string));
            MsgSendTable.Columns.Add("MsgClass", typeof(string));
            MsgSendTable.Columns.Add("SendTime", typeof(DateTime));
            MsgSendTable.Columns.Add("IsFinished", typeof(Boolean));

            //读取群的发送信息
            SQLiteCommand memSQLiteCommand = new SQLiteCommand("", memSQLiteConnection);
            memSQLiteCommand.CommandText = @"SELECT * FROM  MelaGroups";
            //WHERE [IsEnabled]=1

            SQLiteDataReader mySQLiteDataReader = memSQLiteCommand.ExecuteReader();
            while (mySQLiteDataReader.Read())
            {
                String UserName1 = mySQLiteDataReader["UserName"].ToString().Trim();
                String NickName1 = mySQLiteDataReader["NickName"].ToString().Trim();
                String MsgClass = mySQLiteDataReader["MsgClass"].ToString().Trim();
                String SendTimes = mySQLiteDataReader["SendTimes"].ToString().Trim();
                String IsEnabled = mySQLiteDataReader["IsEnabled"].ToString().Trim();
                if (IsEnabled != "True") continue;

                for (int i = 0; i < int.Parse(SendTimes); i++)
                {
                    DateTime SendTime = DateTime.Parse(DateTime.Now.ToString("yyyy-MM-dd ") + r.Next(8, 21) + ":" + r.Next(0, 59) + ":" + r.Next(0, 59));

                    DataRow dr = MsgSendTable.NewRow();
                    dr["UserType"] = 1;
                    dr["UserName"] = UserName1;
                    dr["NickName"] = NickName1;
                    dr["MsgClass"] = MsgClass;
                    dr["SendTime"] = SendTime;
                    if (SendTime < DateTime.Now)
                    {
                        dr["IsFinished"] = true;
                    }
                    else
                    {
                        dr["IsFinished"] = false;
                    }
                    MsgSendTable.Rows.Add(dr);
                }
            }
            mySQLiteDataReader.Close();


            memSQLiteCommand.CommandText = @"SELECT * FROM  MelaFriends";
            SQLiteDataReader mySQLiteDataReader1 = memSQLiteCommand.ExecuteReader();
            while (mySQLiteDataReader1.Read())
            {
                String UserName1 = mySQLiteDataReader1["UserName"].ToString().Trim();
                String NickName1 = mySQLiteDataReader1["NickName"].ToString().Trim();
                String MsgClass = mySQLiteDataReader1["MsgClass"].ToString().Trim();
                String SendTimes = mySQLiteDataReader1["SendTimes"].ToString().Trim();
                String IsEnabled = mySQLiteDataReader1["IsEnabled"].ToString().Trim();
                if (IsEnabled != "True") continue;

                for (int i = 0; i < int.Parse(SendTimes); i++)
                {
                    DateTime SendTime = DateTime.Parse(DateTime.Now.ToString("yyyy-MM-dd ") + r.Next(8, 21) + ":" + r.Next(0, 59) + ":" + r.Next(0, 59));
                    DataRow dr = MsgSendTable.NewRow();
                    dr["UserType"] = 0;
                    dr["UserName"] = UserName1;
                    dr["NickName"] = NickName1;
                    dr["MsgClass"] = MsgClass;
                    dr["SendTime"] = SendTime;

                    if (SendTime < DateTime.Now)
                    {
                        dr["IsFinished"] = true;
                    }
                    else
                    {
                        dr["IsFinished"] = false;
                    }
                    MsgSendTable.Rows.Add(dr);
                }
            }
            mySQLiteDataReader1.Close();

            while (true)
            {
                foreach (DataRow dr in MsgSendTable.Rows)
                {
                    if (Boolean.Parse(dr["IsFinished"].ToString()) == true) continue;

                    if (DateTime.Now > DateTime.Parse(dr["SendTime"].ToString()))
                    {
                        dr["IsFinished"] = true;

                        String Msg = GetOneMelaMessages(dr["MsgClass"].ToString());
                        //发送一条
                        Object command = new
                        {
                            cmd = WX_COMMAND.send_msg.ToString(),
                            data_0 = Msg,
                            data_1 = dr["UserName"],
                            data_2 = "",
                            data_3 = ""

                        };
                        //向服务器发送数据
                        String result = SendCommnadTo_itChat(command);
                        //MessageBox.Show(result);

                        InsetIntoLogs(dr["UserType"].ToString().Trim(), dr["NickName"].ToString().Trim(), Msg, result);
                        //RefreshGroupLogs();
                        //RefreshFriendsLogs();
                        InsetIntoLogs(UserType, NickName, Msg, result);

                    }
                    Thread.Sleep(500);
                }
            }
        }
        private void ShowLoadingFrom()
        {
            Loading ld = new Loading();
            ld.ShowDialog();
        }
        /// <summary>
        /// 检查App.config基础参数配置
        /// 如果缺少配置，则重新创建参数，并使用默认参数设置
        /// </summary>
        private void CheckAppConfig()
        {
            String itChatMasterIP = AppConfig.GetAppSettingValue("itChatMasterIP");
            String itChatMasterPort = AppConfig.GetAppSettingValue("itChatMasterPort");
            String itChatAdminIP = AppConfig.GetAppSettingValue("itChatAdminIP");
            String itChatAdminPort = AppConfig.GetAppSettingValue("itChatAdminPort");

            if (itChatMasterIP == "")
            {
                itChatMasterIP = "127.0.0.1";
                AppConfig.SetAppSettingKeyValue("itChatMasterIP", itChatMasterIP);
            }

            if (itChatMasterPort == "")
            {
                itChatMasterPort = "19990";
                AppConfig.SetAppSettingKeyValue("itChatMasterPort", itChatMasterPort);
            }

            if (itChatAdminIP == "")
            {
                itChatAdminIP = "127.0.0.1";
                AppConfig.SetAppSettingKeyValue("itChatAdminIP", itChatAdminIP);
            }
            if (itChatAdminPort == "")
            {
                itChatAdminPort = "19991";
                AppConfig.SetAppSettingKeyValue("itChatAdminPort", itChatAdminPort);
            }
        }

        private void CommandHashTableInit()
        {
            foreach (string s in Enum.GetNames(typeof(WX_COMMAND)))
            {
                CommandHashTable.Add(s, false);
            }
        }

        private void Start_WebServers()
        {
            HttpServer httpServer;
            httpServer = new MyHttpServer(int.Parse(AppConfig.GetAppSettingValue("itChatAdminPort")));
            thread = new Thread(new ThreadStart(httpServer.listen));
            thread.Start();
        }

        private void GetWxUid_CheckDataBase()
        {
            Object command = new
            {
                cmd = WX_COMMAND.search_friends.ToString(),
                data_0 = "",
                data_1 = "",
                data_2 = "",
                data_3 = ""
            };

            //获取Uid,设置数据库名称
            while (itChatDatabase == "")
            {
                Loading_Msg = "向itChatMaster发送请求......";
                String msg = SendCommnadTo_itChat(command);
                Loading_Msg = "得到回应......";
                if (msg == "")
                {
                    Loading_Msg = "itChatMaster有误......";
                    Thread.Sleep(1000);
                    continue;
                }
                JObject json = JObject.Parse(msg);
                Loading_Msg = "itChatMaster运行正常......";
                if (!Directory.Exists(dir_database))
                {
                    Directory.CreateDirectory(dir_database);
                }
                itChatDatabase = Path.Combine(dir_database, json["Uin"].ToString().Trim() + ".db");
                WxUserName = json["UserName"].ToString().Trim();
                Loading_Msg = "获得登录的微信ID：" + WxUserName;
                WxNickName = json["NickName"].ToString().Trim();
                Loading_Msg = "获得登录的微信名：" + WxNickName;
            }
            //检查创建数据库
            Loading_Msg = "检查本地数据库......";
            SQLiteConnection mySQLiteConnection = new SQLiteConnection("Data Source=" + itChatDatabase);
            try
            {
                mySQLiteConnection.Open();

                Loading_Msg = "检查本地数据库,创建内存表......";
                SQLiteCommand mySQLiteCommand = new SQLiteCommand("", mySQLiteConnection);
                SQLiteCommand memSQLiteCommand = new SQLiteCommand("", memSQLiteConnection);

                //检查本地数据库,创建内存表
                foreach (String tableString in TableArray)
                {
                    mySQLiteCommand.CommandText = tableString;
                    memSQLiteCommand.CommandText = tableString;

                    mySQLiteCommand.ExecuteNonQuery();
                    memSQLiteCommand.ExecuteNonQuery();
                }

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            finally
            {
                mySQLiteConnection.Close();
            }

            Loading_Msg = "加载本地数据库......";
            LoadDataBaseToMem();

            Loading_Msg = "加载发送消息分类......";
            //RefreshMsgClass();
            Loading_OK = true;
        }


        public static void Do_WxMessge(String msg)
        {
            //开启新线程处理收到的消息
            Thread t = new Thread(delegate () { DoWith_itChatMasterMsg(msg); });
            t.Start();
        }

        private void button3_Click(object sender, EventArgs e)
        {
            FormStatistics fs = new FormStatistics();
            fs.Location = new Point(this.Location.X, this.Height);
            fs.ShowDialog();
        }

        private void button2_Click(object sender, EventArgs e)
        {
            FromGroupAdmin fg = new FromGroupAdmin();
            fg.Location = new Point(this.Location.X, this.Height);
            fg.ShowDialog();
        }



        private void button5_Click(object sender, EventArgs e)
        {
            FormSetting fs = new FormSetting();
            fs.Location = new Point(this.Location.X, this.Height);
            fs.ShowDialog();
        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            Thread_Allow_Running = false;
            //不管什么线程都被强制退出，把程序结束的很干净。
            System.Environment.Exit(0);
        }
        private void LoadDataBaseToMem()
        {
            //加载数据库数据
            ArrayList TableList = new ArrayList();
            ArrayList TableInfo = new ArrayList();
            ArrayList ColumnsName = new ArrayList();
            ArrayList ColumnsData = new ArrayList();
            SQLiteConnection mySQLiteConnection = new SQLiteConnection("Data Source=" + itChatDatabase);

            try
            {
                mySQLiteConnection.Open();
                //取出所有数据表名称
                SQLiteCommand memSQLiteCommand = new SQLiteCommand("", memSQLiteConnection);
                SQLiteCommand mySQLiteCommand = new SQLiteCommand("", mySQLiteConnection);

                Loading_Msg = "获取数据库中的表名......";
                memSQLiteCommand.CommandText = "select name from sqlite_master where type='table'";
                SQLiteDataReader mySQLiteDataReader = memSQLiteCommand.ExecuteReader();
                while (mySQLiteDataReader.Read())
                {
                    TableList.Add(mySQLiteDataReader["name"].ToString().Trim());
                }
                mySQLiteDataReader.Close();


                foreach (String tableName in TableList)
                {
                    if ("sqlite_sequence" == tableName) continue;

                    Loading_Msg = "处理表[" + tableName + "]中的数据......";
                    TableInfo.Clear();
                    //列出所有表列名
                    ColumnsName.Clear();
                    memSQLiteCommand.CommandText = "PRAGMA table_info([" + tableName + "])";
                    SQLiteDataReader mySQLiteDataReader1 = memSQLiteCommand.ExecuteReader();
                    while (mySQLiteDataReader1.Read())
                    {
                        ColumnsName.Add(mySQLiteDataReader1["name"].ToString().Trim());
                    }
                    mySQLiteDataReader1.Close();

                    //列出表中一列数据
                    mySQLiteCommand.CommandText = "SELECT * FROM " + tableName;
                    SQLiteDataReader mySQLiteDataReader2 = mySQLiteCommand.ExecuteReader();
                    while (mySQLiteDataReader2.Read())
                    {
                        ColumnsData.Clear();
                        String InsertCommandString = "INSERT INTO " + tableName + "(";
                        String InsertValueString = ") VALUES (@";
                        foreach (string clo in ColumnsName)
                        {
                            String aa = mySQLiteDataReader2[clo].ToString().Trim();
                            ColumnsData.Add(mySQLiteDataReader2[clo].ToString().Trim());
                            InsertCommandString += clo + ",";
                            InsertValueString += clo + ",@";
                        }
                        InsertCommandString = InsertCommandString.Substring(0, InsertCommandString.Length - 1) + InsertValueString.Substring(0, InsertValueString.Length - 2) + ")";
                        memSQLiteCommand.CommandText = InsertCommandString;

                        for (int i = 0; i < ColumnsName.Count; i++)
                        {
                            memSQLiteCommand.Parameters.Add(new SQLiteParameter("@" + ColumnsName[i]));
                            memSQLiteCommand.Parameters["@" + ColumnsName[i]].Value = ColumnsData[i];
                        }
                        memSQLiteCommand.ExecuteNonQuery();
                        memSQLiteCommand.Parameters.Clear();
                    }
                    mySQLiteDataReader2.Close();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            finally
            {
                mySQLiteConnection.Close();
            }
        }

        public static String SendCommnadTo_itChat(Object command)
        {
            try
            {
                String sendString = new JavaScriptSerializer().Serialize(command);
                WebClient wc = new WebClient();
                StringBuilder postData = new StringBuilder();
                postData.Append(sendString);
                byte[] sendData = Encoding.GetEncoding("utf-8").GetBytes(postData.ToString());
                wc.Headers.Add("Content-Type", "application/json");
                wc.Headers.Add("ContentLength", sendData.Length.ToString());
                byte[] recData = wc.UploadData("http://" + AppConfig.GetAppSettingValue("itChatMasterIP") + ":" + AppConfig.GetAppSettingValue("itChatMasterPort") + "/", sendData);
                return System.Web.HttpUtility.UrlDecode(Encoding.GetEncoding("utf-8").GetString(recData).Replace(@"\u", "%u"));
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                return "";
            }

        }

        /// <summary>
        /// 写入维系服务器发送过来的Json字符串，
        /// </summary>
        /// <param name="msg"></param>
        /// <param name="profix"></param>
        /// <param name="Indentation"></param>
        public static void Write_Log(String msg, String profix = "", int Indentation = 0)
        {
            String ASCII_LETTERS = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
            String fileName = "";

            if (!Directory.Exists(dir_logs))
            {
                Directory.CreateDirectory(dir_logs);
            }
            Random r = new Random();
            for (int i = 0; i < 20; i++)
            {
                int index = r.Next(0, ASCII_LETTERS.Length - 1);
                fileName += ASCII_LETTERS[index];
            }

            fileName = Path.Combine(dir_logs, profix + "_" + fileName + ".txt");
            if (Indentation == 0)
            {
                File.AppendAllText(fileName, msg);
            }
            else
            {
                File.AppendAllText(fileName, ConvertJsonString(msg));
            }
        }

        /// <summary>
        /// Json字符串美化
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string ConvertJsonString(string str)
        {
            //格式化json字符串
            JsonSerializer serializer = new JsonSerializer();
            TextReader tr = new StringReader(str);
            JsonTextReader jtr = new JsonTextReader(tr);
            object obj = serializer.Deserialize(jtr);
            if (obj != null)
            {
                StringWriter textWriter = new StringWriter();
                JsonTextWriter jsonWriter = new JsonTextWriter(textWriter)
                {
                    Formatting = Formatting.Indented,
                    Indentation = 2,
                    IndentChar = ' '
                };
                serializer.Serialize(jsonWriter, obj);
                return textWriter.ToString();
            }
            else
            {
                return str;
            }
        }



        public static void WriteToDBInDisk(SQLiteCommand mySQLiteCommand1)
        {
            SQLiteConnection mySQLiteConnection = new SQLiteConnection("Data Source=" + itChatDatabase);
            SQLiteCommand mySQLiteCommand = (SQLiteCommand)mySQLiteCommand1.Clone();
            mySQLiteCommand.Connection = mySQLiteConnection;
            try
            {
                mySQLiteConnection.Open();
                mySQLiteCommand.Connection = mySQLiteConnection;
                mySQLiteCommand.ExecuteNonQuery();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            finally
            {
                mySQLiteConnection.Close();
            }

        }

        private void button1_Click(object sender, EventArgs e)
        {
            FormFriendAdmin myFormFriendAdmin = new FormFriendAdmin();
            myFormFriendAdmin.Location = new Point(this.Location.X, this.Height);
            myFormFriendAdmin.Show();
        }

        /// <summary>
        /// 初始化数据库文件，
        /// </summary>
        private void Datatable_Init()
        {
            TableArray.Add(@"create table if not exists [MaleMarketing](
        [ID] INTEGER PRIMARY KEY AUTOINCREMENT, 
        [Msg] TEXT, 
        [IsEnable] BOOL DEFAULT 0, 
        [MsgClass] INT DEFAULT 0, 
        [AddTime] DATETEXT default (datetime('now', 'localtime')),
        [NickName] TEXT)");

            TableArray.Add(@"create table if not exists [MelaRobot](
        [ID] INTEGER PRIMARY KEY AUTOINCREMENT, 
        [group_name] TEXT(100), 
        [my_nickname] TEXT(100), 
        [robot_enabled] BOOL DEFAULT 0, 
        [robot_start_time] TEXT, 
        [robot_endtime] TEXT, 
        [robot_send_content] TEXT(100), 
        [robot_send_interval] INT DEFAULT 60, 
        [stranger_filtered] BOOL DEFAULT 0, 
        [add_time] DATETEXT default (datetime('now', 'localtime')))");

            TableArray.Add(@"CREATE TABLE if not exists [MelaContract](
        [ID] INTEGER PRIMARY KEY AUTOINCREMENT, 
        [NickName] TEXT(100), 
        [IsEnabled] BOOL DEFAULT 0, 
        [SendTime] TEXT, 
        [SendContent] TEXT(50), 
        [LastSendTime] DATETEXT, 
        [IsRunning] BOOL DEFAULT 0, 
        [ErrorMsg] TEXT, 
        [upate_time] DATETEXT default (datetime('now', 'localtime')), 
        [add_time] DATETEXT default (datetime('now', 'localtime')))");

            TableArray.Add(@"CREATE TABLE if not exists [MelaStranger](
        [ID] INTEGER PRIMARY KEY AUTOINCREMENT, 
        [UserName] TEXT, 
        [RemarkPYQuanPin] TEXT, 
        [DisplayName] TEXT, 
        [KeyWord] TEXT, 
        [PYInitial] TEXT, 
        [Uin] TEXT, 
        [MemberList] TEXT, 
        [MemberStatus] TEXT, 
        [PYQuanPin] TEXT, 
        [RemarkPYInitial] TEXT, 
        [NickName] TEXT, 
        [AttrStatus] TEXT,
        [IsSend] BOOL DEFAULT 0,
        [IsFilterd] BOOL DEFAULT 0,
        [UpdateDataTime] DATETEXT default (datetime('now', 'localtime')))");

            TableArray.Add(@"CREATE TABLE if not exists [MelaFriends](
        [ID] INTEGER PRIMARY KEY AUTOINCREMENT, 
        [UserName] TEXT(100), 
        [City] TEXT(50), 
        [DisplayName] TEXT(100), 
        [UniFriend] TEXT, 
        [OwnerUin] TEXT, 
        [MemberList] TEXT, 
        [PYQuanPin] TEXT, 
        [RemarkPYInitial] TEXT, 
        [Uin] TEXT, 
        [AppAccountFlag] TEXT, 
        [VerifyFlag] TEXT, 
        [Province] TEXT, 
        [KeyWord] TEXT, 
        [RemarkName] TEXT, 
        [PYInitial] TEXT, 
        [ChatRoomId] TEXT, 
        [HideInputBarFlag] TEXT, 
        [HeadImgFlag] TEXT, 
        [EncryChatRoomId] TEXT, 
        [AttrStatus] TEXT, 
        [SnsFlag] TEXT, 
        [MemberCount] TEXT,
        [IsOwner] TEXT,
        [WebWxPluginSwitch] TEXT, 
        [Alias] TEXT, 
        [Signature] TEXT, 
        [ContactFlag] TEXT, 
        [NickName] TEXT, 
        [RemarkPYQuanPin] TEXT, 
        [HeadImgUrl] TEXT, 
        [Sex] TEXT, 
        [StarFriend] TEXT, 
        [Statues] TEXT, 
        [MsgClass] TEXT, 
        [IsEnabled] BOOL DEFAULT 0, 
        [IsRunning] BOOL DEFAULT 0, 
        [IsSkipOneDay] BOOL DEFAULT 0, 
        [SendTimes] INTEGER DEFAULT 0, 
        [UpdateDataTime] DATETEXT default (datetime('now', 'localtime')))");

            TableArray.Add(@"CREATE TABLE if not exists [MelaGroups](
        [ID] INTEGER PRIMARY KEY AUTOINCREMENT, 
        [UserName] TEXT, 
        [City] TEXT, 
        [DisplayName] TEXT, 
        [UniFriend] TEXT, 
        [Self] TEXT, 
        [PYQuanPin] TEXT, 
        [RemarkPYInitial] TEXT, 
        [Sex] TEXT, 
        [AppAccountFlag] TEXT, 
        [VerifyFlag] TEXT, 
        [Province] TEXT, 
        [KeyWord] TEXT, 
        [RemarkName] TEXT, 
        [PYInitial] TEXT, 
        [IsOwner] TEXT, 
        [ChatRoomId] TEXT, 
        [HideInputBarFlag] TEXT, 
        [EncryChatRoomId] TEXT, 
        [AttrStatus] TEXT, 
        [SnsFlag] TEXT, 
        [MemberCount] TEXT, 
        [OwnerUin] TEXT, 
        [Alias] TEXT, 
        [IsAdmin] TEXT, 
        [Signature] TEXT, 
        [ContactFlag] TEXT, 
        [NickName] TEXT, 
        [RemarkPYQuanPin] TEXT, 
        [HeadImgUrl] TEXT, 
        [Uin] TEXT, 
        [StarFriend] TEXT, 
        [Statues] TEXT, 
        [MsgClass] TEXT, 
        [IsEnabled] BOOL DEFAULT 0, 
        [IsRunning] BOOL DEFAULT 0, 
        [IsGetStrangers] BOOL DEFAULT 0, 
        [SendTimes] INTEGER DEFAULT 0, 
        [UpdateDataTime] DATETEXT DEFAULT (datetime('now','localtime')))");

            TableArray.Add(@"CREATE TABLE if not exists [MelaGroupClass](
        [ID] INTEGER PRIMARY KEY AUTOINCREMENT, 
        [ClassID] INTEGER, 
        [ClassName] TEXT, 
        [UpdateDataTime] DATETEXT default (datetime('now', 'localtime')))");

            TableArray.Add(@"CREATE TABLE if not exists [MelaFriendClass](
        [ID] INTEGER PRIMARY KEY AUTOINCREMENT, 
        [ClassID] INTEGER, 
        [ClassName] TEXT, 
        [UpdateDataTime] DATETEXT default (datetime('now', 'localtime')))");

            TableArray.Add(@"CREATE TABLE if not exists [MelaSendMsgLog](
        [ID] INTEGER PRIMARY KEY AUTOINCREMENT,
        [UserType] TEXT, 
        [NickName] TEXT, 
        [SendMsg] TEXT,
        [SendResult] TEXT, 
        [RawResult] TEXT, 
        [UpdateDataTime] DATETEXT default (datetime('now', 'localtime')))");

            TableArray.Add(@"CREATE TABLE if not exists [MelaMessages](
        [ID] INTEGER PRIMARY KEY AUTOINCREMENT,
        [IsEnabled] BOOL DEFAULT 0,  
        [MsgClass] TEXT, 
        [Messages] TEXT, 
        [UpdateDataTime] DATETEXT default (datetime('now', 'localtime')))");

            TableArray.Add(@"CREATE TABLE if not exists [MelaMessagesClass](
        [ID] INTEGER PRIMARY KEY AUTOINCREMENT,
        [ClassName] TEXT, 
        [UpdateDataTime] DATETEXT default (datetime('now', 'localtime')))");

            TableArray.Add(@"CREATE TABLE if not exists [MelaFriendsSendMsgLog](
        [ID] INTEGER PRIMARY KEY AUTOINCREMENT,
        [UserID] TEXT, 
        [SendDateTime] DATETEXT,
        [MsgID] INTEGER, 
        [SendResult] INTEGER, 
        [UpdateDataTime] DATETEXT default (datetime('now', 'localtime')))");

            TableArray.Add(@"CREATE TABLE if not exists [MelaCalender](
        [ID] INTEGER PRIMARY KEY AUTOINCREMENT,
        [UserType] TEXT, 
        [NickName] TEXT, 
        [IntervalType] TEXT,
        [StartDateTime] DATETEXT, 
        [IntervalTimes] INTEGER, 
        [IntervalOther1] TEXT, 
        [IntervalOther2] TEXT, 
        [UpdateDataTime] DATETEXT default (datetime('now', 'localtime')))");
        }


        /// <summary>
        /// 记录发送消息后的日志
        /// </summary>
        /// <param name="UserType"></param>
        /// <param name="NickName"></param>
        /// <param name="SendMsg"></param>
        /// <param name="SendResult"></param>
        public static void InsetIntoLogs(String UserType, String NickName, String SendMsg, String SendResult)
        {
            SQLiteCommand mySQLiteCommand = new SQLiteCommand("", memSQLiteConnection);
            mySQLiteCommand.CommandText = "INSERT INTO MelaSendMsgLog(UserType,NickName,SendMsg,SendResult,RawResult) VALUES (@UserType,@NickName,@SendMsg,@SendResult,@RawResult)";

            JObject json = JObject.Parse(SendResult);
            String Ret = json["BaseResponse"]["Ret"].ToString().Trim();
            mySQLiteCommand.Parameters.Add(new SQLiteParameter("@UserType"));
            mySQLiteCommand.Parameters.Add(new SQLiteParameter("@NickName"));
            mySQLiteCommand.Parameters.Add(new SQLiteParameter("@SendMsg"));
            mySQLiteCommand.Parameters.Add(new SQLiteParameter("@SendResult"));
            mySQLiteCommand.Parameters.Add(new SQLiteParameter("@RawResult"));

            mySQLiteCommand.Parameters["@UserType"].Value = UserType;
            mySQLiteCommand.Parameters["@NickName"].Value = NickName;
            mySQLiteCommand.Parameters["@SendMsg"].Value = SendMsg;
            if (Ret == "0")
            {
                mySQLiteCommand.Parameters["@SendResult"].Value = "OK";
            }
            else
            {
                mySQLiteCommand.Parameters["@SendResult"].Value = "FAIL";

            }
            mySQLiteCommand.Parameters["@RawResult"].Value = SendResult;
            mySQLiteCommand.ExecuteNonQuery();
            WriteToDBInDisk(mySQLiteCommand);
            mySQLiteCommand.Parameters.Clear();
        }

        /// <summary>
        /// 提取一条消息
        /// </summary>
        /// <param name="MsgClass"></param>
        /// <returns></returns>
        public static String GetOneMelaMessages(String MsgClass)
        {
            String[] msg = MsgClass.Split('|');
            String result = "";
            String Filter = "";
            foreach (String m in msg)
            {
                Filter += "Messages LIKE '%" + m + "%' OR ";
            }

            Filter = Filter.Substring(0, Filter.Length - 3);

            //Random r = new Random();
            SQLiteCommand mySQLiteCommand = new SQLiteCommand("", memSQLiteConnection);
            mySQLiteCommand.CommandText = "SELECT count(*) FROM MelaMessages WHERE  (" + Filter + ")";
            object i = mySQLiteCommand.ExecuteScalar();
            mySQLiteCommand.Parameters.Clear();

            if (int.Parse(i.ToString().Trim()) == 0)
            {
                return "";
            }

            mySQLiteCommand.CommandText = "SELECT Messages FROM MelaMessages WHERE  (" + Filter + ") LIMIT " + r.Next(0, int.Parse(i.ToString()));
            SQLiteDataReader mySQLiteDataReader = mySQLiteCommand.ExecuteReader();
            while (mySQLiteDataReader.Read())
            {
                result = mySQLiteDataReader["Messages"].ToString().Trim();
            }
            return result;
        }



        private void button23_Click(object sender, EventArgs e)
        {
            FormMsgAdmin fm = new FormMsgAdmin();
            fm.Location = new Point(this.Location.X, this.Height);
            fm.Show();
        }


        public static String PostMsgtoWeb(String MsgClass, String Msg)
        {
            object command = new
            {
                action = "upload_msg",
                msg_class = MsgClass,
                msg = Msg
            };

            try
            {
                String sendString = new JavaScriptSerializer().Serialize(command);
                WebClient wc = new WebClient();
                StringBuilder postData = new StringBuilder();
                postData.Append(sendString);
                byte[] sendData = Encoding.GetEncoding("utf-8").GetBytes(postData.ToString());
                wc.Headers.Add("Content-Type", "application/json");
                wc.Headers.Add("ContentLength", sendData.Length.ToString());
                byte[] recData = wc.UploadData("http://" + AppConfig.GetAppSettingValue("itChatMsgIP") + ":" + AppConfig.GetAppSettingValue("itChatMsgPort") + "/", sendData);
                return System.Web.HttpUtility.UrlDecode(Encoding.GetEncoding("utf-8").GetString(recData).Replace(@"\u", "%u"));
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                return "";
            }
        }

        private void button21_Click(object sender, EventArgs e)
        {
            FormStranger fs = new FormStranger();
            fs.Location = new Point(this.Location.X, this.Height);
            fs.Show();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            int x = SystemInformation.PrimaryMonitorSize.Width;
            int x1 = this.Width;
            this.Location = new Point((x - x1) / 2, 0);
        }

        public static String GetGroupUserNameWithID(String ID)
        {
            SQLiteCommand mySQLiteCommand = new SQLiteCommand("", memSQLiteConnection);
            mySQLiteCommand.CommandText = "SELECT UserName FROM MelaGroups WHERE ID=" + ID;
            SQLiteDataReader mySQLiteDataReader = mySQLiteCommand.ExecuteReader();
            if (mySQLiteDataReader.Read())
            {
                return mySQLiteDataReader["UserName"].ToString().Trim();
            }
            else
            {
                return "";
            }
        }

        public static String GetStrangerUserNameByID(String ID)
        {
            SQLiteCommand mySQLiteCommand = new SQLiteCommand("", memSQLiteConnection);
            mySQLiteCommand.CommandText = "SELECT UserName FROM MelaStranger WHERE ID=" + ID;
            SQLiteDataReader mySQLiteDataReader = mySQLiteCommand.ExecuteReader();
            if (mySQLiteDataReader.Read())
            {
                return mySQLiteDataReader["UserName"].ToString().Trim();
            }
            else
            {
                return "";
            }
        }

        private void button4_Click(object sender, EventArgs e)
        {
            FormSysLogs fs = new FormSysLogs();
            fs.Show();
        }
    }
    enum WX_COMMAND
    {
        get_friends,
        get_contact,
        get_chatrooms,
        get_head_img,
        get_mps,
        update_chatroom,
        update_friend,
        set_alias,
        set_pinned,
        set_chatroom_name,
        add_friend,
        add_member_into_chatroom,
        create_chatroom,
        delete_member_from_chatroom,
        send_raw_msg,
        send_msg,
        send_file,
        send_image,
        send_video,
        send,
        upload_file,
        dump_login_status,
        search_friends,
        search_chatrooms,
        search_mps,
    }
}
